// import mysql2 from 'mysql2'
import mysql2 from 'mysql2/promise'
import fs from 'node:fs'
import path, {dirname} from 'node:path'
import jsYaml from 'js-yaml'
import express from 'express'
// esm 无法使用 cjs的__dirname,__filename
// import {fileURLToPath} from 'node:url'
// const __filename = fileURLToPath(import.meta.url)
// const __dirname = dirname(__filename)
// 或者直接'./db.config.yaml'
const dbConfigStr = fs.readFileSync('./db.config.yaml', 'utf-8')
const dbConfig = jsYaml.load(dbConfigStr)
const sql = await mysql2.createConnection({
    ...dbConfig.db
})
// setTimeout(async () => {
//     const list = await sql.query('SELECT * FROM `user`')
//     console.log(list);
// })

// express启动服务
const app = express()
app.use(express.json())
const port = 3000
app.use('*', (req, res,next) => {
    res.setHeader('Access-Control-Allow-Origin', '*')
    next()
})
// 查
app.get('/list', async (req, res) => {
    const [data] = await sql.query('select * from user')
//     console.log(list);
    res.send(data)
})
// 单个查
app.get('/get/:userId', async (req, res) => {
    const {userId} = req.params
    console.log('userId',userId);
    // const [data] = await sql.query(`select * from user where id=${userId}`)
    const [data] = await sql.query('select * from user where id=?', [userId])
//     console.log(list);
    res.send(data)
})
// 增
app.post('/add', async (req, res) => {
    console.log('req.body',req.body);
    const {name, age, hobby, address} = req.body
    const result = await sql.query('insert into user(name, age, hobby, address) values(?,?,?,?)',[name, age, hobby, address])
    res.send({
        code: 1,
        message: 'ok'
    })
})
// 改
app.post('/update',async (req, res) => {
    const {name, age, hobby, address, id} = req.body
    console.log(name, age, hobby, address, id);
    const result = await sql.query(`update user set name=?,age=?,hobby=?,address=? where id=?`, [name, age, hobby, address, id])
    res.json({
        code: 200,
        message: 'update success'
    })
})
// 删
app.post('/del/:userId', async (req,res) => {
    const {userId} = req.params
    const [data] = await sql.query('delete from user where id=?', [userId])
    res.json({
        code: 200,
        message: 'delete success'
    })
})

app.listen(port, () => {
    console.log('server is runing at http://localhost:', port);
})